package com.readboottest.chain.client;


import com.readboottest.entity.Book;
import com.readboottest.entity.BookCatalogue;
import com.readboottest.enums.WebsiteEnum;
import com.readboottest.util.HttpUtilS;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.readboottest.constant.NovelConstant.*;


/**
 * @author zhanghuiyong
 * @创建时间 2019年05月28日
 * @描述: 起点小说搜索
 **/
@Service
public class SearchWebsiteQidian extends SearchWebsite {

    public static void main(String[] args) {
        SearchWebsiteQidian qidian = new SearchWebsiteQidian();
        qidian.readingNovel(NOVEL_NAME_WSCQ, 1);
    }

    /**
     * 网站搜索接口
     *
     * @param keyWord 关键字（小说名称）
     * @return book 书籍实体
     */
    @Override
    public Book searchWebsite(String keyWord) {
        //转码
        String keyWordEncode = null;
        try {
            keyWordEncode = URLEncoder.encode(keyWord, CODE_UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String searchUrl = WebsiteEnum.WEBSITE_QIDIAN.getSearchUrl() + keyWordEncode;
        String searchResult = HttpUtilS.doGet(searchUrl, CODE_UTF_8);
        //book-img-text
        //解析文档
        Document doc = Jsoup.parse(searchResult);
        //获取class
        Elements elementsByClass = doc.getElementsByClass("book-mid-info");
        //默认获取第一个class
        Element firstElement = elementsByClass.first();
        //根据a标签 获取bookUrl
        Elements bookUrlByTag = firstElement.getElementsByTag(STRING_TAG_A);

        //根据cite 标签获取书籍名称
        String bookName = firstElement.getElementsByTag(STRING_TAG_A).first().text();
        System.out.println("查询书籍名称:" + bookName);
        //根据属性获取书籍地址
        String bookUrl = STRING_HTTPS + bookUrlByTag.first().attributes().get(STRING_TAG_HREF);
        //根据intro class 获取书籍简介
        String bookSynopsis = firstElement.getElementsByClass("intro").text();


        Book qdBook = new Book();
        qdBook.setBookName(bookName);
        qdBook.setBookUrl(bookUrl);
        qdBook.setBookSynopsis(bookSynopsis);
//        //现在不需要模糊查询，如果检索的和查询结果的不一致就返回结果
//        if (!keyWord.equals(bookName)) {
//            return null;
//        }
        return qdBook;

    }

    /**
     * 获取书籍目录
     *
     * @param book 书籍名称实体
     * @return book 书籍目录实体
     */
    @Override
    public Book getNovelCatalogueList(Book book) {
        List<BookCatalogue> catalogueList = new ArrayList<>();
        //书籍编号计数器
        Integer codeNumber = 1;

        String searchResult = HttpUtilS.doGet(book.getBookUrl(), CODE_UTF_8);
        //解析文档
        Document doc = Jsoup.parse(searchResult);
        //根据volume-wrap class 获取书籍目录
        Element cataloguesByFirst = doc.getElementsByClass("volume-wrap").first();

        //cf class 获取免费章节和VIP章节
        Elements cataloguesByCf = cataloguesByFirst.getElementsByClass("cf");

        //免费章节目录
        Element cataloguesByNVIP = cataloguesByCf.first();
        //根据a 标签获取书籍目录内容
        Elements nCatalogues = cataloguesByNVIP.getElementsByTag(STRING_TAG_A);
        for (Element nCatalogue : nCatalogues) {
            /** 非VIP章节处理  */
            addCatalogueList(nCatalogue, catalogueList, BOOT_TYPE_NVIP, codeNumber);
            codeNumber++;
        }
        Element cataloguesByVIP = cataloguesByCf.last();
        Elements vCatalogues = cataloguesByVIP.getElementsByTag(STRING_TAG_A);
        for (Element vCatalogue : vCatalogues) {
            /** VIP章节处理  */
            addCatalogueList(vCatalogue, catalogueList, BOOT_TYPE_VIP, codeNumber);
            codeNumber++;
        }
        book.setCatalogueList(catalogueList);
        return book;
    }


    /**
     * 获取章节内容
     *
     * @param bookCatalogue 章节实体
     * @return content 书籍内容
     */
    @Override
    public BookCatalogue getNovelContent(BookCatalogue bookCatalogue) {
        String searchResult = HttpUtilS.doGet(bookCatalogue.getHref(), CODE_UTF_8);
        //解析文档
        Document doc = Jsoup.parse(searchResult);
        /**
         * class 空格处理
         * @see https://m635674608.iteye.com/blog/2379946
         * */
        //根据read-content j_readContent class 获取书籍目录
        Element cataloguesByFirst = doc.getElementsByClass("read-content").first();
        String chapterContent = cataloguesByFirst.toString();
        bookCatalogue.setChapterContent(chapterContent);
        return bookCatalogue;
    }

    @Override
    public String websiteType() {
        return WebsiteEnum.WEBSITE_QIDIAN.getWebsiteName();
    }


    public static void addCatalogueList(Element catalogue, List<BookCatalogue> catalogueList, String bookType, Integer codeNumber) {
        //书籍内容预处理
        BookCatalogue bookCatalogue = new BookCatalogue();
        bookCatalogue.setType(bookType);
        bookCatalogue.setId(codeNumber);
        //获取书籍章节的地址
        String href = STRING_HTTPS + catalogue.attributes().get(STRING_TAG_HREF);
        //获取章节标题
        String title = catalogue.text();
        bookCatalogue.setTitle(title);
        bookCatalogue.setHref(href);
        catalogueList.add(bookCatalogue);
    }
}
